<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import { recipeApi } from '../request'
import type { Recipe } from '../request/api/recipe'

const recipes = ref<Recipe[]>([])
const isLoading = ref(false)
const error = ref('')

// 获取所有菜谱
const fetchAllRecipes = async () => {
  try {
    isLoading.value = true
    error.value = ''

    const response = await recipeApi.getAllRecipes()
    recipes.value = response
  } catch (e) {
    console.error('获取菜谱列表失败:', e)
    error.value = '获取菜谱列表失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}

// 获取菜品类型中文名称
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    meat: '荤菜',
    vegetable: '素菜',
    soup: '汤类',
    other: '其他'
  }
  return typeMap[type] || '其他'
}

onMounted(fetchAllRecipes)
</script>

<template>
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="flex justify-between items-center mb-8">
      <h1 class="text-3xl font-bold text-gray-900">所有菜谱</h1>
      <RouterLink
        to="/create-recipe"
        class="btn btn-primary"
      >
        创建新菜谱
      </RouterLink>
    </div>
    
    <div v-if="isLoading" class="text-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"></div>
      <p class="mt-4 text-gray-600">加载菜谱中...</p>
    </div>

    <div v-else-if="error" class="text-center py-12">
      <p class="text-red-500">{{ error }}</p>
      <button
        @click="fetchAllRecipes"
        class="mt-4 btn btn-primary"
      >
        重试
      </button>
    </div>

    <div
      v-else
      class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
    >
      <RouterLink
        v-for="recipe in recipes"
        :key="recipe.id"
        :to="`/recipe/${recipe.id}`"
        class="card hover:shadow-lg transition-shadow duration-200"
      >
        <img
          :src="recipe.imageUrl"
          :alt="recipe.name"
          class="w-full h-48 object-cover"
        />
        <div class="p-4">
          <h3 class="text-xl font-semibold text-gray-900">{{ recipe.name }}</h3>
          <span
            class="mt-2 inline-block px-2 py-1 text-xs font-medium rounded-full"
            :class="{
              'bg-red-100 text-red-600': recipe.type === 'meat',
              'bg-green-100 text-green-600': recipe.type === 'vegetable',
              'bg-blue-100 text-blue-600': recipe.type === 'soup',
              'bg-gray-100 text-gray-600': recipe.type === 'other'
            }"
          >
            {{ getTypeText(recipe.type) }}
          </span>
        </div>
      </RouterLink>
    </div>

    <div v-if="recipes.length === 0 && !isLoading && !error" class="text-center py-12">
      <p class="text-gray-500">暂无菜谱</p>
      <RouterLink
        to="/create-recipe"
        class="mt-4 btn btn-primary inline-block"
      >
        创建第一个菜谱
      </RouterLink>
    </div>
  </div>
</template>